package com.gxa.autoparts.portal.listener;

import com.gxa.autoparts.core.common.ExceptionCode;
import com.gxa.autoparts.core.exception.BusinessException;
import com.gxa.autoparts.core.pojo.SystemMessage;
import com.gxa.autoparts.core.util.JsonUtil;
import com.gxa.autoparts.portal.service.SystemMessageService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author ：looker
 * @date ：Created in 2022/1/12 9:38
 */
@Component
@Transactional(rollbackFor = Throwable.class)
public class SystemMessageListener implements ChannelAwareMessageListener {

    @Autowired
    SystemMessageService systemMessageService;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String[] split = message.toString().split("'");
        //(Body:'"{\"msg\":{\"id\":1,\"title\":\"test1\",\"context\":\"我是第二个测试内容\",\"sendTime\":\"2022-01-12 10:15:00\"}}"' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, expiration=1002222000, priority=0, redelivered=true, receivedExchange=demo.exchange, receivedRoutingKey=demo.routeKey, deliveryTag=173, consumerTag=amq.ctag-F3ML0IMjDa914MJM3be6_w, consumerQueue=demo.queue])
        if(split.length>2){
            SystemMessage messageOfString = getMessageOfString(split[1]);
            systemMessageService.saveMessage(messageOfString);
            channel.basicAck(deliveryTag,true);
        }else {
            channel.basicReject(deliveryTag, true);//为true会重新放回队列
            throw new BusinessException(ExceptionCode.INFO_ERROE);
        }

    }

    public SystemMessage getMessageOfString(String s){
        //String substring = s.substring(1, s.length() - 1);
        SystemMessage systemMessage = JsonUtil.readToObject(s, SystemMessage.class);
        return systemMessage;
    }
}
